"""
Flask微服务示例 - 展示微服务架构和服务间通信
包含用户服务、订单服务、通知服务等微服务组件
"""

from flask import Flask, request, jsonify, g
import os
import sys
import time
import asyncio
import threading
from datetime import datetime, timedelta
from typing import Dict, Any, List, Optional
from enum import Enum
import json
from dataclasses import dataclass, asdict
from concurrent.futures import ThreadPoolExecutor

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from python_backend_toolkit.auth import JWTAuth, PasswordManager
from python_backend_toolkit.cache import CacheManager, MemoryCache
from python_backend_toolkit.database import Base, BaseModel, DatabaseSession
from python_backend_toolkit.logging import get_logger, setup_logging
from python_backend_toolkit.http_client import HTTPClient, AsyncHTTPClient
from python_backend_toolkit.utils import generate_uuid, format_datetime
from python_backend_toolkit.api.responses import (
    SuccessResponse, ErrorResponse, CreatedResponse
)
from python_backend_toolkit.api.exceptions import (
    ValidationError, NotFoundError, UnauthorizedError
)

from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, Float, Enum as SQLEnum


# ========================================================================
# 数据模型和枚举
# ========================================================================

class OrderStatus(Enum):
    """订单状态"""
    PENDING = "pending"
    CONFIRMED = "confirmed"
    PROCESSING = "processing"
    SHIPPED = "shipped"
    DELIVERED = "delivered"
    CANCELLED = "cancelled"


class NotificationType(Enum):
    """通知类型"""
    EMAIL = "email"
    SMS = "sms"
    PUSH = "push"
    WEBHOOK = "webhook"


@dataclass
class ServiceEvent:
    """服务事件"""
    event_id: str
    event_type: str
    service_name: str
    data: Dict[str, Any]
    timestamp: str
    
    def to_dict(self):
        return asdict(self)


class User(BaseModel):
    """用户模型"""
    __tablename__ = 'microservice_users'
    
    username = Column(String(50), unique=True, nullable=False)
    email = Column(String(200), unique=True, nullable=False)
    password_hash = Column(String(255), nullable=False)
    first_name = Column(String(50))
    last_name = Column(String(50))
    phone = Column(String(20))
    address = Column(Text)


class Order(BaseModel):
    """订单模型"""
    __tablename__ = 'microservice_orders'
    
    order_number = Column(String(50), unique=True, nullable=False)
    user_id = Column(Integer, nullable=False)
    total_amount = Column(Float, nullable=False)
    status = Column(SQLEnum(OrderStatus), default=OrderStatus.PENDING)
    items = Column(Text)  # JSON格式的商品列表
    shipping_address = Column(Text)
    notes = Column(Text)


class Notification(BaseModel):
    """通知模型"""
    __tablename__ = 'microservice_notifications'
    
    user_id = Column(Integer, nullable=False)
    notification_type = Column(SQLEnum(NotificationType), nullable=False)
    title = Column(String(200), nullable=False)
    content = Column(Text, nullable=False)
    sent = Column(Boolean, default=False)
    sent_at = Column(DateTime)
    metadata = Column(Text)  # JSON格式的额外数据


# ========================================================================
# 服务基类
# ========================================================================

class BaseService:
    """微服务基类"""
    
    def __init__(self, service_name: str, port: int):
        self.service_name = service_name
        self.port = port
        self.logger = get_logger(service_name)
        self.http_client = HTTPClient()
        self.cache = MemoryCache()
        self.event_handlers = {}
        
        # 服务注册表（简化版）
        self.service_registry = {
            "user_service": "http://localhost:5010",
            "order_service": "http://localhost:5011",
            "notification_service": "http://localhost:5012",
            "gateway": "http://localhost:5009"
        }
    
    def register_event_handler(self, event_type: str, handler):
        """注册事件处理器"""
        if event_type not in self.event_handlers:
            self.event_handlers[event_type] = []
        self.event_handlers[event_type].append(handler)
    
    def emit_event(self, event_type: str, data: Dict[str, Any]):
        """发送事件"""
        event = ServiceEvent(
            event_id=generate_uuid(),
            event_type=event_type,
            service_name=self.service_name,
            data=data,
            timestamp=datetime.utcnow().isoformat()
        )
        
        self.logger.info(
            "Event emitted",
            event_id=event.event_id,
            event_type=event_type,
            service_name=self.service_name
        )
        
        # 异步处理事件
        threading.Thread(
            target=self._process_event,
            args=(event,),
            daemon=True
        ).start()
    
    def _process_event(self, event: ServiceEvent):
        """处理事件"""
        # 通知其他服务
        for service_name, service_url in self.service_registry.items():
            if service_name != self.service_name.lower().replace(" ", "_"):
                try:
                    self.http_client.post(
                        f"{service_url}/events",
                        json=event.to_dict(),
                        timeout=5
                    )
                except Exception as e:
                    self.logger.warning(
                        "Failed to notify service",
                        service_name=service_name,
                        error=str(e)
                    )
    
    def handle_event(self, event: ServiceEvent):
        """处理接收到的事件"""
        handlers = self.event_handlers.get(event.event_type, [])
        
        for handler in handlers:
            try:
                handler(event)
            except Exception as e:
                self.logger.error(
                    "Event handler error",
                    event_id=event.event_id,
                    event_type=event.event_type,
                    error=str(e)
                )
    
    def call_service(self, service_name: str, endpoint: str, method: str = 'GET', 
                    data: Dict = None, headers: Dict = None) -> Optional[Dict]:
        """调用其他服务"""
        service_url = self.service_registry.get(service_name)
        if not service_url:
            self.logger.error("Service not found", service_name=service_name)
            return None
        
        url = f"{service_url}{endpoint}"
        
        try:
            if method.upper() == 'GET':
                response = self.http_client.get(url, headers=headers)
            elif method.upper() == 'POST':
                response = self.http_client.post(url, json=data, headers=headers)
            elif method.upper() == 'PUT':
                response = self.http_client.put(url, json=data, headers=headers)
            elif method.upper() == 'DELETE':
                response = self.http_client.delete(url, headers=headers)
            else:
                return None
            
            if response.status_code == 200:
                return response.json()
            else:
                self.logger.warning(
                    "Service call failed",
                    service_name=service_name,
                    endpoint=endpoint,
                    status_code=response.status_code
                )
                return None
                
        except Exception as e:
            self.logger.error(
                "Service call error",
                service_name=service_name,
                endpoint=endpoint,
                error=str(e)
            )
            return None


# ========================================================================
# 用户服务
# ========================================================================

class UserService(BaseService):
    """用户服务"""
    
    def __init__(self):
        super().__init__("User Service", 5010)
        self.password_manager = PasswordManager()
        
        # 初始化数据库
        self.db_session = DatabaseSession(
            database_url="sqlite:///microservice_users.db",
            echo=False
        )
        self.db_session.create_tables()
    
    def create_user(self, username: str, email: str, password: str, 
                   first_name: str = None, last_name: str = None,
                   phone: str = None, address: str = None) -> Dict[str, Any]:
        """创建用户"""
        session = self.db_session.get_session()
        
        try:
            # 检查用户名和邮箱唯一性
            existing_user = session.query(User).filter(
                (User.username == username) | (User.email == email)
            ).first()
            
            if existing_user:
                raise ValidationError("Username or email already exists")
            
            # 创建用户
            password_hash = self.password_manager.hash_password(password)
            
            user = User(
                username=username,
                email=email,
                password_hash=password_hash,
                first_name=first_name,
                last_name=last_name,
                phone=phone,
                address=address
            )
            
            session.add(user)
            session.commit()
            
            user_data = user.to_dict()
            user_data.pop('password_hash', None)
            
            # 发送用户创建事件
            self.emit_event("user_created", {
                "user_id": user.id,
                "username": username,
                "email": email
            })
            
            self.logger.info(
                "User created",
                user_id=user.id,
                username=username
            )
            
            return user_data
            
        finally:
            session.close()
    
    def get_user(self, user_id: int) -> Optional[Dict[str, Any]]:
        """获取用户信息"""
        # 先从缓存获取
        cache_key = f"user:{user_id}"
        cached_user = self.cache.get(cache_key)
        if cached_user:
            return cached_user
        
        session = self.db_session.get_session()
        
        try:
            user = session.query(User).filter(User.id == user_id).first()
            if not user:
                return None
            
            user_data = user.to_dict()
            user_data.pop('password_hash', None)
            
            # 缓存用户信息
            self.cache.set(cache_key, user_data, ttl=300)
            
            return user_data
            
        finally:
            session.close()
    
    def authenticate_user(self, username: str, password: str) -> Optional[Dict[str, Any]]:
        """用户认证"""
        session = self.db_session.get_session()
        
        try:
            user = session.query(User).filter(User.username == username).first()
            if not user:
                return None
            
            if not self.password_manager.verify_password(password, user.password_hash):
                return None
            
            user_data = user.to_dict()
            user_data.pop('password_hash', None)
            
            # 发送用户登录事件
            self.emit_event("user_logged_in", {
                "user_id": user.id,
                "username": username
            })
            
            return user_data
            
        finally:
            session.close()


# ========================================================================
# 订单服务
# ========================================================================

class OrderService(BaseService):
    """订单服务"""
    
    def __init__(self):
        super().__init__("Order Service", 5011)
        
        # 初始化数据库
        self.db_session = DatabaseSession(
            database_url="sqlite:///microservice_orders.db",
            echo=False
        )
        self.db_session.create_tables()
        
        # 注册事件处理器
        self.register_event_handler("user_created", self._handle_user_created)
    
    def _handle_user_created(self, event: ServiceEvent):
        """处理用户创建事件"""
        user_id = event.data.get('user_id')
        username = event.data.get('username')
        
        self.logger.info(
            "User created event received",
            user_id=user_id,
            username=username
        )
        
        # 可以在这里初始化用户相关的订单数据
    
    def create_order(self, user_id: int, items: List[Dict], 
                    shipping_address: str, notes: str = None) -> Dict[str, Any]:
        """创建订单"""
        session = self.db_session.get_session()
        
        try:
            # 验证用户存在
            user_data = self.call_service("user_service", f"/users/{user_id}")
            if not user_data:
                raise ValidationError("User not found")
            
            # 计算总金额
            total_amount = sum(item.get('price', 0) * item.get('quantity', 1) for item in items)
            
            # 生成订单号
            order_number = f"ORD-{generate_uuid()[:8].upper()}"
            
            # 创建订单
            order = Order(
                order_number=order_number,
                user_id=user_id,
                total_amount=total_amount,
                status=OrderStatus.PENDING,
                items=json.dumps(items),
                shipping_address=shipping_address,
                notes=notes
            )
            
            session.add(order)
            session.commit()
            
            order_data = order.to_dict()
            order_data['items'] = items
            
            # 发送订单创建事件
            self.emit_event("order_created", {
                "order_id": order.id,
                "order_number": order_number,
                "user_id": user_id,
                "total_amount": total_amount
            })
            
            self.logger.info(
                "Order created",
                order_id=order.id,
                order_number=order_number,
                user_id=user_id
            )
            
            return order_data
            
        finally:
            session.close()
    
    def get_order(self, order_id: int) -> Optional[Dict[str, Any]]:
        """获取订单信息"""
        session = self.db_session.get_session()
        
        try:
            order = session.query(Order).filter(Order.id == order_id).first()
            if not order:
                return None
            
            order_data = order.to_dict()
            order_data['items'] = json.loads(order.items) if order.items else []
            
            return order_data
            
        finally:
            session.close()
    
    def update_order_status(self, order_id: int, status: OrderStatus) -> bool:
        """更新订单状态"""
        session = self.db_session.get_session()
        
        try:
            order = session.query(Order).filter(Order.id == order_id).first()
            if not order:
                return False
            
            old_status = order.status
            order.status = status
            order.updated_at = datetime.utcnow()
            
            session.commit()
            
            # 发送订单状态更新事件
            self.emit_event("order_status_updated", {
                "order_id": order.id,
                "order_number": order.order_number,
                "user_id": order.user_id,
                "old_status": old_status.value,
                "new_status": status.value
            })
            
            self.logger.info(
                "Order status updated",
                order_id=order.id,
                old_status=old_status.value,
                new_status=status.value
            )
            
            return True
            
        finally:
            session.close()


# ========================================================================
# 通知服务
# ========================================================================

class NotificationService(BaseService):
    """通知服务"""
    
    def __init__(self):
        super().__init__("Notification Service", 5012)
        
        # 初始化数据库
        self.db_session = DatabaseSession(
            database_url="sqlite:///microservice_notifications.db",
            echo=False
        )
        self.db_session.create_tables()
        
        # 注册事件处理器
        self.register_event_handler("user_created", self._handle_user_created)
        self.register_event_handler("order_created", self._handle_order_created)
        self.register_event_handler("order_status_updated", self._handle_order_status_updated)
    
    def _handle_user_created(self, event: ServiceEvent):
        """处理用户创建事件"""
        user_id = event.data.get('user_id')
        username = event.data.get('username')
        email = event.data.get('email')
        
        # 发送欢迎通知
        self.create_notification(
            user_id=user_id,
            notification_type=NotificationType.EMAIL,
            title="欢迎注册",
            content=f"欢迎 {username} 注册我们的服务！",
            metadata={"email": email}
        )
    
    def _handle_order_created(self, event: ServiceEvent):
        """处理订单创建事件"""
        order_id = event.data.get('order_id')
        order_number = event.data.get('order_number')
        user_id = event.data.get('user_id')
        total_amount = event.data.get('total_amount')
        
        # 发送订单确认通知
        self.create_notification(
            user_id=user_id,
            notification_type=NotificationType.EMAIL,
            title="订单确认",
            content=f"您的订单 {order_number} 已创建，总金额：¥{total_amount}",
            metadata={"order_id": order_id, "order_number": order_number}
        )
    
    def _handle_order_status_updated(self, event: ServiceEvent):
        """处理订单状态更新事件"""
        order_id = event.data.get('order_id')
        order_number = event.data.get('order_number')
        user_id = event.data.get('user_id')
        new_status = event.data.get('new_status')
        
        # 发送状态更新通知
        status_messages = {
            "confirmed": "已确认",
            "processing": "处理中",
            "shipped": "已发货",
            "delivered": "已送达",
            "cancelled": "已取消"
        }
        
        status_text = status_messages.get(new_status, new_status)
        
        self.create_notification(
            user_id=user_id,
            notification_type=NotificationType.PUSH,
            title="订单状态更新",
            content=f"您的订单 {order_number} 状态已更新为：{status_text}",
            metadata={"order_id": order_id, "order_number": order_number, "status": new_status}
        )
    
    def create_notification(self, user_id: int, notification_type: NotificationType,
                          title: str, content: str, metadata: Dict = None) -> Dict[str, Any]:
        """创建通知"""
        session = self.db_session.get_session()
        
        try:
            notification = Notification(
                user_id=user_id,
                notification_type=notification_type,
                title=title,
                content=content,
                metadata=json.dumps(metadata) if metadata else None
            )
            
            session.add(notification)
            session.commit()
            
            notification_data = notification.to_dict()
            notification_data['metadata'] = metadata
            
            # 异步发送通知
            threading.Thread(
                target=self._send_notification,
                args=(notification.id,),
                daemon=True
            ).start()
            
            self.logger.info(
                "Notification created",
                notification_id=notification.id,
                user_id=user_id,
                type=notification_type.value
            )
            
            return notification_data
            
        finally:
            session.close()
    
    def _send_notification(self, notification_id: int):
        """发送通知（模拟）"""
        session = self.db_session.get_session()
        
        try:
            notification = session.query(Notification).filter(
                Notification.id == notification_id
            ).first()
            
            if not notification:
                return
            
            # 模拟发送过程
            time.sleep(1)
            
            # 标记为已发送
            notification.sent = True
            notification.sent_at = datetime.utcnow()
            session.commit()
            
            self.logger.info(
                "Notification sent",
                notification_id=notification_id,
                type=notification.notification_type.value
            )
            
        except Exception as e:
            self.logger.error(
                "Failed to send notification",
                notification_id=notification_id,
                error=str(e)
            )
        finally:
            session.close()
    
    def get_user_notifications(self, user_id: int, limit: int = 20) -> List[Dict[str, Any]]:
        """获取用户通知"""
        session = self.db_session.get_session()
        
        try:
            notifications = session.query(Notification).filter(
                Notification.user_id == user_id
            ).order_by(Notification.created_at.desc()).limit(limit).all()
            
            result = []
            for notification in notifications:
                data = notification.to_dict()
                data['metadata'] = json.loads(notification.metadata) if notification.metadata else {}
                result.append(data)
            
            return result
            
        finally:
            session.close()


# ========================================================================
# API网关
# ========================================================================

def create_api_gateway() -> Flask:
    """创建API网关"""
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'microservice-gateway-secret'
    
    # 初始化日志
    setup_logging()
    logger = get_logger("APIGateway")
    
    # 初始化认证
    jwt_auth = JWTAuth(secret_key=app.config['SECRET_KEY'])
    
    # 服务实例
    user_service = UserService()
    order_service = OrderService()
    notification_service = NotificationService()
    
    # 中间件
    @app.before_request
    def before_request():
        g.request_id = generate_uuid()
        g.start_time = time.time()
        
        logger.info(
            "Gateway request started",
            request_id=g.request_id,
            method=request.method,
            path=request.path
        )
    
    @app.after_request
    def after_request(response):
        duration = time.time() - g.start_time
        
        logger.info(
            "Gateway request completed",
            request_id=g.request_id,
            status_code=response.status_code,
            duration=duration
        )
        
        return response
    
    # 认证中间件
    def require_auth(f):
        def decorated_function(*args, **kwargs):
            auth_header = request.headers.get('Authorization')
            if not auth_header or not auth_header.startswith('Bearer '):
                raise UnauthorizedError("Authentication required")
            
            token = auth_header.split(' ')[1]
            try:
                payload = jwt_auth.decode_token(token)
                g.current_user_id = payload.get('user_id')
            except Exception:
                raise UnauthorizedError("Invalid token")
            
            return f(*args, **kwargs)
        
        decorated_function.__name__ = f.__name__
        return decorated_function
    
    # 异常处理
    @app.errorhandler(ValidationError)
    def handle_validation_error(e):
        return jsonify(ErrorResponse.create(message=str(e)).dict()), 400
    
    @app.errorhandler(NotFoundError)
    def handle_not_found_error(e):
        return jsonify(ErrorResponse.create(message=str(e)).dict()), 404
    
    @app.errorhandler(UnauthorizedError)
    def handle_unauthorized_error(e):
        return jsonify(ErrorResponse.create(message=str(e)).dict()), 401
    
    # ========================================================================
    # 用户相关API
    # ========================================================================
    
    @app.route('/auth/register', methods=['POST'])
    def register():
        """用户注册"""
        try:
            data = request.get_json()
            
            user_data = user_service.create_user(
                username=data.get('username'),
                email=data.get('email'),
                password=data.get('password'),
                first_name=data.get('first_name'),
                last_name=data.get('last_name'),
                phone=data.get('phone'),
                address=data.get('address')
            )
            
            # 生成JWT令牌
            token = jwt_auth.generate_token({
                'user_id': user_data['id'],
                'username': user_data['username']
            })
            
            response = CreatedResponse.create(
                data={
                    "user": user_data,
                    "token": token
                },
                message="User registered successfully"
            )
            return jsonify(response.dict()), 201
            
        except ValidationError as e:
            raise
        except Exception as e:
            logger.error("Registration error", error=str(e))
            return jsonify(ErrorResponse.create(
                message="Registration failed"
            ).dict()), 500
    
    @app.route('/auth/login', methods=['POST'])
    def login():
        """用户登录"""
        try:
            data = request.get_json()
            
            user_data = user_service.authenticate_user(
                username=data.get('username'),
                password=data.get('password')
            )
            
            if not user_data:
                raise UnauthorizedError("Invalid credentials")
            
            # 生成JWT令牌
            token = jwt_auth.generate_token({
                'user_id': user_data['id'],
                'username': user_data['username']
            })
            
            response = SuccessResponse.create(
                data={
                    "user": user_data,
                    "token": token
                },
                message="Login successful"
            )
            return jsonify(response.dict())
            
        except UnauthorizedError as e:
            raise
        except Exception as e:
            logger.error("Login error", error=str(e))
            return jsonify(ErrorResponse.create(
                message="Login failed"
            ).dict()), 500
    
    @app.route('/users/<int:user_id>', methods=['GET'])
    @require_auth
    def get_user(user_id: int):
        """获取用户信息"""
        try:
            user_data = user_service.get_user(user_id)
            if not user_data:
                raise NotFoundError("User not found")
            
            response = SuccessResponse.create(
                data={"user": user_data},
                message="User retrieved successfully"
            )
            return jsonify(response.dict())
            
        except NotFoundError as e:
            raise
        except Exception as e:
            logger.error("Get user error", error=str(e))
            return jsonify(ErrorResponse.create(
                message="Failed to retrieve user"
            ).dict()), 500
    
    # ========================================================================
    # 订单相关API
    # ========================================================================
    
    @app.route('/orders', methods=['POST'])
    @require_auth
    def create_order():
        """创建订单"""
        try:
            data = request.get_json()
            
            order_data = order_service.create_order(
                user_id=g.current_user_id,
                items=data.get('items', []),
                shipping_address=data.get('shipping_address'),
                notes=data.get('notes')
            )
            
            response = CreatedResponse.create(
                data={"order": order_data},
                message="Order created successfully"
            )
            return jsonify(response.dict()), 201
            
        except ValidationError as e:
            raise
        except Exception as e:
            logger.error("Create order error", error=str(e))
            return jsonify(ErrorResponse.create(
                message="Failed to create order"
            ).dict()), 500
    
    @app.route('/orders/<int:order_id>', methods=['GET'])
    @require_auth
    def get_order(order_id: int):
        """获取订单信息"""
        try:
            order_data = order_service.get_order(order_id)
            if not order_data:
                raise NotFoundError("Order not found")
            
            response = SuccessResponse.create(
                data={"order": order_data},
                message="Order retrieved successfully"
            )
            return jsonify(response.dict())
            
        except NotFoundError as e:
            raise
        except Exception as e:
            logger.error("Get order error", error=str(e))
            return jsonify(ErrorResponse.create(
                message="Failed to retrieve order"
            ).dict()), 500
    
    @app.route('/orders/<int:order_id>/status', methods=['PUT'])
    @require_auth
    def update_order_status(order_id: int):
        """更新订单状态"""
        try:
            data = request.get_json()
            status_str = data.get('status')
            
            try:
                status = OrderStatus(status_str)
            except ValueError:
                raise ValidationError("Invalid order status")
            
            success = order_service.update_order_status(order_id, status)
            if not success:
                raise NotFoundError("Order not found")
            
            response = SuccessResponse.create(
                message="Order status updated successfully"
            )
            return jsonify(response.dict())
            
        except (ValidationError, NotFoundError) as e:
            raise
        except Exception as e:
            logger.error("Update order status error", error=str(e))
            return jsonify(ErrorResponse.create(
                message="Failed to update order status"
            ).dict()), 500
    
    # ========================================================================
    # 通知相关API
    # ========================================================================
    
    @app.route('/notifications', methods=['GET'])
    @require_auth
    def get_notifications():
        """获取用户通知"""
        try:
            limit = min(int(request.args.get('limit', 20)), 100)
            
            notifications = notification_service.get_user_notifications(
                user_id=g.current_user_id,
                limit=limit
            )
            
            response = SuccessResponse.create(
                data={"notifications": notifications},
                message="Notifications retrieved successfully"
            )
            return jsonify(response.dict())
            
        except Exception as e:
            logger.error("Get notifications error", error=str(e))
            return jsonify(ErrorResponse.create(
                message="Failed to retrieve notifications"
            ).dict()), 500
    
    # ========================================================================
    # 事件处理
    # ========================================================================
    
    @app.route('/events', methods=['POST'])
    def handle_event():
        """处理服务间事件"""
        try:
            event_data = request.get_json()
            event = ServiceEvent(**event_data)
            
            # 分发事件到相应服务
            if event.service_name != "User Service":
                user_service.handle_event(event)
            if event.service_name != "Order Service":
                order_service.handle_event(event)
            if event.service_name != "Notification Service":
                notification_service.handle_event(event)
            
            return jsonify({"status": "event processed"})
            
        except Exception as e:
            logger.error("Event handling error", error=str(e))
            return jsonify({"status": "error", "message": str(e)}), 500
    
    # ========================================================================
    # 健康检查和信息
    # ========================================================================
    
    @app.route('/health', methods=['GET'])
    def health_check():
        """健康检查"""
        return jsonify({
            "status": "healthy",
            "timestamp": datetime.utcnow().isoformat(),
            "services": {
                "user_service": "running",
                "order_service": "running",
                "notification_service": "running"
            }
        })
    
    @app.route('/info', methods=['GET'])
    def app_info():
        """应用信息"""
        return jsonify({
            "name": "Microservice API Gateway",
            "version": "1.0.0",
            "description": "微服务架构示例 - API网关",
            "services": [
                "用户服务 (User Service)",
                "订单服务 (Order Service)",
                "通知服务 (Notification Service)"
            ],
            "features": [
                "服务间通信",
                "事件驱动架构",
                "JWT认证",
                "服务发现",
                "负载均衡",
                "统一API网关"
            ],
            "endpoints": {
                "auth": [
                    "POST /auth/register - 用户注册",
                    "POST /auth/login - 用户登录"
                ],
                "users": [
                    "GET /users/<id> - 获取用户信息"
                ],
                "orders": [
                    "POST /orders - 创建订单",
                    "GET  /orders/<id> - 获取订单信息",
                    "PUT  /orders/<id>/status - 更新订单状态"
                ],
                "notifications": [
                    "GET /notifications - 获取用户通知"
                ]
            },
            "architecture": {
                "pattern": "Microservices",
                "communication": "HTTP + Events",
                "data_consistency": "Eventual Consistency",
                "service_discovery": "Static Registry"
            }
        })
    
    return app


if __name__ == '__main__':
    app = create_api_gateway()
    
    print("=" * 60)
    print("Flask Microservice Example")
    print("=" * 60)
    print("微服务架构演示:")
    print("  服务组件:")
    print("    - API网关 (端口 5009)")
    print("    - 用户服务 (端口 5010)")
    print("    - 订单服务 (端口 5011)")
    print("    - 通知服务 (端口 5012)")
    print()
    print("  API端点:")
    print("    认证:")
    print("      POST /auth/register - 用户注册")
    print("      POST /auth/login - 用户登录")
    print("    用户:")
    print("      GET /users/<id> - 获取用户信息")
    print("    订单:")
    print("      POST /orders - 创建订单")
    print("      GET  /orders/<id> - 获取订单信息")
    print("      PUT  /orders/<id>/status - 更新订单状态")
    print("    通知:")
    print("      GET /notifications - 获取用户通知")
    print()
    print("  特性:")
    print("    - 服务间通信")
    print("    - 事件驱动架构")
    print("    - 数据一致性")
    print("    - 服务发现")
    print("    - 统一认证")
    print("    - 异步通知")
    print("=" * 60)
    
    app.run(
        host='0.0.0.0',
        port=5009,
        debug=True
    )